package com.mxpio.erp.technology.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mxpio.erp.common.technology.entity.ItemGroup;
import com.mxpio.erp.common.technology.service.ItemGroupService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.CriteriaUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "ItemGroupService", tags = { "物料组接口" })
@RestController
@RequestMapping("/erp/common/item/group/")
public class ItemGroupController {
	
	@Autowired
	private ItemGroupService itemGroupsSerivce;

	@GetMapping("tree")
	@ApiOperation(value = "物料组树", notes = "获取物料组", httpMethod = "GET")
	public Result<List<ItemGroup>> list(String criteria) throws UnsupportedEncodingException {
		Criteria c = CriteriaUtils.json2Criteria(criteria);
		List<ItemGroup> itemGroups = itemGroupsSerivce.tree(ItemGroup.class, c);
		return Result.OK(itemGroups);
	}
	
	@GetMapping("list/{groupCode}")
	@ApiOperation(value = "根据groupCode获取物料组", notes = "根据groupCode获取物料组", httpMethod = "GET")
	public Result<ItemGroup> getById(@PathVariable(name = "groupCode", required = true) String groupCode) {
		ItemGroup itemGroup = itemGroupsSerivce.getById(ItemGroup.class, groupCode);
		return Result.OK(itemGroup);
	}
	
	@PostMapping("add")
	@ApiOperation(value = "新增物料组", notes = "新增物料组", httpMethod = "POST")
	public Result<ItemGroup> add(@RequestBody ItemGroup itemGroup) {
		itemGroupsSerivce.save(itemGroup);
		return Result.OK(itemGroup);
	}
	
	@PutMapping("edit")
	@ApiOperation(value = "编辑物料组", notes = "编辑物料组（全量）", httpMethod = "PUT")
	public Result<ItemGroup> edit(@RequestBody ItemGroup itemGroup) {
		itemGroupsSerivce.update(itemGroup);
		return Result.OK(itemGroup);
	}
	
	@DeleteMapping("remove/{groupCode}")
	@ApiOperation(value = "删除物料组", notes = "删除物料组", httpMethod = "DELETE")
	public Result<ItemGroup> remove(@PathVariable(name = "groupCode", required = true) String groupCode) {
		String ids[] = groupCode.split(",");
		for(String key : ids){
			itemGroupsSerivce.delete(ItemGroup.class, key);
		}
		return Result.OK();
	}
	
}
